﻿using MediatR;
using Service.Auth.Domain.AggregatesModel;
using Service.Core.Repository;
using Service.Core.Repository.Attribute;
using Service.Framework;
using Service.Auth.Api.Application.Command;
using Service.Auth.Api.Application.Query;
using Service.Core.Redis.Aop.Cache;

namespace Service.Auth.Api.Application.Handler.CommandHandler;

// Regular CommandHandler
/// <summary>
/// 
/// </summary>
/// <param name="systemRepository"></param>
public class SystemCommandHandler(IRepository<TSystem> systemRepository) : IRequestHandler<CreateSystemCommand, bool>
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    /// <exception cref="LogicErrorException"></exception>
    [UnitOfWork]
    [RemoveRedisCacheInterceptor(cacheKey: $"{nameof(SystemQueryService)}:{nameof(SystemQueryService.QuerySystemList)}")]
    public async Task<bool> Handle(CreateSystemCommand request, CancellationToken cancellationToken)
    {
        var systemDto = request.System;

        if (await systemRepository.AnyAsync(s => s.ClientId.Equals(systemDto.SystemNum), cancellationToken))
            throw new LogicErrorException($"系统编号：{systemDto.SystemNum}重复，请修改后重试。");
        var system = new TSystem(systemDto.SystemName, systemDto.SystemNum, systemDto.Remarks, systemDto.SecretKey);
        return await systemRepository.InsertAsync(system, cancellationToken);
    }
}

